﻿using System;

namespace Bricks
{

    /// <summary>
    /// 
    /// </summary>
    /// <typeparam name="TKernel"></typeparam>
    public class DisposableLazyFacadeBase<TKernel> : LazyFacadeBase<TKernel>
    {

        /// <summary>
        /// 
        /// </summary>
        private bool _disposing = false;

        /// <summary>
        /// 
        /// </summary>
        /// <param name="lazyKernel"></param>
        protected DisposableLazyFacadeBase(Lazy<TKernel> lazyKernel) :
            base(lazyKernel) { }

        /// <summary>
        /// 
        /// </summary>
        public void Dispose()
        {
            Dispose(true);

            GC.SuppressFinalize(this);
        }

        /// <summary>
        /// 
        /// </summary>
        /// <param name="disposing"></param>
        protected virtual void Dispose(bool disposing)
        {
            if (!_disposing)
            {
                if (disposing)
                {
                    _disposing = true;

                    if (Kernel.IsValueCreated)
                    {
                        IDisposable disposable = Kernel.Value as IDisposable;

                        if (disposable != null)
                        {
                            disposable.Dispose();
                        }
                    }
                }
            }
        }

        /// <summary>
        /// 
        /// </summary>
        ~DisposableLazyFacadeBase()
        {
            Dispose(false);
        }
    }
}
